package com.quanshu.shop.goods.view;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.shop.base.data.BroadcastReciverAction;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;
import com.quanshu.shop.brocastreciver.CartUpdateBrocarstReciver;
import com.quanshu.shop.goods.adapter.MyCartAdapter;
import com.quanshu.shop.goods.entity.CartBaseEntity;
import com.quanshu.shop.goods.entity.MyCartEntity;
import com.quanshu.shop.goods.inf.CartUpdateListener;
import com.quanshu.shop.main.api.ShopMainIF;
import com.quanshu.shop.order.SubmitOrderActivity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CartActivity extends BaseActivity implements CartUpdateListener {

    @BindView(R.id.cart_title)
    BaseTitleBar cartTitle;
    @BindView(R.id.cart_rl)
    RecyclerView cartRl;
    @BindView(R.id.cart_foot_cl1)
    ConstraintLayout cartFootCl1;
    @BindView(R.id.cart_foot_cl2)
    TextView cartFootCl2;
    @BindView(R.id.cart_foot_cl3)
    TextView cartFootCl3;
    @BindView(R.id.cart_foot)
    ConstraintLayout cartFoot;
    @BindView(R.id.cart_img_all)
    ImageView cartImgAll;
    @BindView(R.id.cart_foot_txt1)
    TextView cartFootTxt1;
    @BindView(R.id.cart_foot_txt2)
    TextView cartFootTxt2;
    @BindView(R.id.cart_foot_txt3)
    TextView cartFootTxt3;
    @BindView(R.id.cart_foot_fl2)
    ConstraintLayout cartFootFl2;
    @BindView(R.id.cart_foot_delete)
    TextView cartFootDelete;
    private MyCartAdapter myCartAdapter;
    private List<CartBaseEntity> entityList;
    private Context mContext;
    private boolean isSelelctAll = false;
    private boolean isEdit = false;
    private List<CartBaseEntity> entitySubmitList;
    private CartUpdateBrocarstReciver cartUpdateBrocarstReciver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(cartTitle).init();
        mContext = this;
        initView();
    }

    @OnClick(R.id.cart_foot_cl1)
    void selectAll() {
        if (myCartAdapter != null) {
            if (isSelelctAll) {
                setItemState(false);
                cartImgAll.setImageResource(R.drawable.icon_unselected_1_2_0);
                isSelelctAll = false;
            } else {
                setItemState(true);
                cartImgAll.setImageResource(R.drawable.icon_selected_1_2_0);
                isSelelctAll = true;
            }
        }
        sumMoney();
    }

    private void setItemState(boolean state) {
        if (myCartAdapter.getData().size() <= 0) {
            return;
        }
        for (int a = 0; a < myCartAdapter.getData().size(); a++) {
            myCartAdapter.getData().get(a).setSelect(state);
        }
        myCartAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.cart_foot_delete)
    void deleteCartGoods() {
        List<CartBaseEntity> list = getSubmitData();
        if (list.size() > 0) {
            List<String> stringList = new ArrayList<>();
            for (int a = 0; a < myCartAdapter.getData().size(); a++) {
                StringBuilder stringBuilder = new StringBuilder();
                if (myCartAdapter.getData().get(a).isSelect()) {
                    String type = TextUtils.isEmpty(myCartAdapter.getData().get(a).getGoodsListEntity().getSpec_array()) ? "goods" : "product";
                    if (TextUtils.isEmpty(myCartAdapter.getData().get(a).getGoodsListEntity().getSpec_array())) {
                        stringBuilder.append(myCartAdapter.getData().get(a).getGoodsListEntity().getGoods_id()).append(",").append(type);
                    } else {
                        stringBuilder.append(myCartAdapter.getData().get(a).getGoodsListEntity().getProduct_id()).append(",").append(type);
                    }
                    stringList.add(stringBuilder.toString());
                }
            }
            String result = JSON.toJSONString(stringList);
            NetClient.getInstance().getShopService(ShopMainIF.class).deleteCartGoods(AppUtils.getSignParams(currentUser.getId(), result), currentUser.getId(), result).compose(new BaseTransformer<>(this)).subscribe(new BaseObserver<BaseResponse<String>>() {
                @Override
                public void onSuccess(BaseResponse<String> response) {
                    Intent intent = new Intent();
                    intent.setAction(BroadcastReciverAction.UPDATE_MY_CART);
                    sendBroadcast(intent);
                }
            });
        } else {
            ToastHelper.toast("请勾商品！");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
        unregisterReceiver(cartUpdateBrocarstReciver);
    }

    private void initView() {
        cartUpdateBrocarstReciver = new CartUpdateBrocarstReciver().setCartUpdateListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastReciverAction.UPDATE_MY_CART);
        registerReceiver(cartUpdateBrocarstReciver, intentFilter);
        RxViewHelper.getInstance().clicks(cartFootCl3, aVoid ->
                {
                    List<CartBaseEntity> list = getSubmitData();
                    if (list.size() > 0) {
                        Bundle bundle = new Bundle();
                        bundle.putString("order_state", "0");
                        bundle.putSerializable("order_data", (Serializable) list);
                        Log.d("打印", "initView: " + getSubmitData());
                        BaseTool.goActivity(this, SubmitOrderActivity.class, bundle);
                    } else {
                        ToastHelper.toast("请勾商品！");
                    }

                }

        );
        entityList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        cartRl.setLayoutManager(linearLayoutManager);
        cartTitle.setLeftImage(R.drawable.icon_back_black_2_0)
                .setCenterText("购物车")
                .setRightText("管理")
                .setRightTextColor(Color.parseColor("#eb2624"))
                .setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
                    @Override
                    public void onclickLeft() {
                        finish();
                    }

                    @Override
                    public void onclickRight() {
                        if (!isEdit) {
                            cartTitle.setRightText("取消").setRightTextColor(Color.parseColor("#999999"));
                            cartFootFl2.setVisibility(View.INVISIBLE);
                            cartFootCl3.setVisibility(View.INVISIBLE);
                            cartFootDelete.setVisibility(View.VISIBLE);
                            isEdit = true;
                        } else {
                            cartTitle.setRightText("管理").setRightTextColor(Color.parseColor("#eb2624"));
                            cartFootFl2.setVisibility(View.VISIBLE);
                            cartFootCl3.setVisibility(View.VISIBLE);
                            cartFootDelete.setVisibility(View.INVISIBLE);
                            isEdit = false;
                        }
                    }
                });

        //获取购物车列表
        getCart(false);

    }

    /**
     * 获取购物车
     */
    private void getCart(boolean isRefresh) {
        if (currentUser != null) {
            NetClient.getInstance().getShopService(ShopMainIF.class).getCartListInfo(AppUtils.getSignParams(currentUser.getId()), currentUser.getId())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<MyCartEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<MyCartEntity> response) {
                            if (isRefresh) {
                                entityList = new ArrayList<>();
                            }
                            if(response.getData()==null||response.getData().getGoodsList()==null){
                                return;
                            }
                            for (int a = 0; a < response.getData().getGoodsList().size(); a++) {
                                CartBaseEntity cartBaseEntity = new CartBaseEntity();
                                cartBaseEntity.setGoodsListEntity(response.getData().getGoodsList().get(a));
                                if (Integer.parseInt(response.getData().getGoodsList().get(a).getCount()) > 1) {
                                    cartBaseEntity.setReduce(true);
                                } else {
                                    cartBaseEntity.setReduce(false);
                                }
                                if (Integer.parseInt(response.getData().getGoodsList().get(a).getCount()) == Integer.parseInt(response.getData().getGoodsList().get(a).getStore_nums())) {
                                    cartBaseEntity.setPlus(false);
                                } else {
                                    cartBaseEntity.setPlus(true);
                                }
                                entityList.add(cartBaseEntity);
                            }
                            if (isRefresh) {
                                myCartAdapter.setNewData(entityList);
                                sumMoney();
                            } else {
                                myCartAdapter = new MyCartAdapter(entityList, mContext);
                                myCartAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                    @Override
                                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                        switch (view.getId()) {
                                            case R.id.cart_fl_select:
                                                if (entityList.get(position).isSelect()) {
                                                    entityList.get(position).setSelect(false);
                                                } else {
                                                    entityList.get(position).setSelect(true);
                                                }
                                                break;
                                            case R.id.cart_txt_goods_number3:
                                                //增加数量
                                                if (TextUtils.isEmpty(entityList.get(position).getGoodsListEntity().getSpec_array())) {
                                                    alterGoodsNumber(entityList.get(position).getGoodsListEntity().getSpec_array(), entityList.get(position).getGoodsListEntity().getGoods_id(), Integer.parseInt(entityList.get(position).getGoodsListEntity().getCount()) + 1, position);
                                                } else {
                                                    alterGoodsNumber(entityList.get(position).getGoodsListEntity().getSpec_array(), entityList.get(position).getGoodsListEntity().getProduct_id(), Integer.parseInt(entityList.get(position).getGoodsListEntity().getCount()) + 1, position);
                                                }
                                                break;
                                            case R.id.cart_txt_goods_number1:
                                                //减少数量
                                                if (TextUtils.isEmpty(entityList.get(position).getGoodsListEntity().getSpec_array())) {
                                                    alterGoodsNumber(entityList.get(position).getGoodsListEntity().getSpec_array(), entityList.get(position).getGoodsListEntity().getGoods_id(), Integer.parseInt(entityList.get(position).getGoodsListEntity().getCount()) - 1, position);
                                                } else {
                                                    alterGoodsNumber(entityList.get(position).getGoodsListEntity().getSpec_array(), entityList.get(position).getGoodsListEntity().getProduct_id(), Integer.parseInt(entityList.get(position).getGoodsListEntity().getCount()) - 1, position);
                                                }
                                                break;
                                            case R.id.cart_txt_goods_number2:
                                                //直接修改数量
                                                break;
                                        }
                                        myCartAdapter.notifyDataSetChanged();
                                        sumMoney();
                                    }
                                });
                                cartRl.setAdapter(myCartAdapter);
                            }

                        }
                    });
        }
    }

    //更改购物车数量
    private void alterGoodsNumber(String spec, String goodID, int goodsNumber, int position) {
        String type = TextUtils.isEmpty(spec) ? "goods" : "product";
        NetClient.getInstance().getShopService(ShopMainIF.class).alterCartGoodsNumberInfo(AppUtils.getSignParams(currentUser.getId(), goodID, String.valueOf(goodsNumber), type), currentUser.getId(), goodID, String.valueOf(goodsNumber), type).compose(new BaseTransformer<>(this)).subscribe(new BaseObserver<BaseResponse<String>>() {
            @Override
            public void onFailure(Throwable e) {
                ToastHelper.toast("更改失败");
            }

            @Override
            public void onSuccess(BaseResponse<String> response) {
                myCartAdapter.getData().get(position).getGoodsListEntity().setCount(String.valueOf(goodsNumber));
                if (goodsNumber > 1) {
                    myCartAdapter.getData().get(position).setReduce(true);
                } else {
                    myCartAdapter.getData().get(position).setReduce(false);
                }
                if (goodsNumber == Integer.parseInt(myCartAdapter.getData().get(position).getGoodsListEntity().getStore_nums())) {
                    myCartAdapter.getData().get(position).setPlus(false);
                } else {
                    myCartAdapter.getData().get(position).setPlus(true);
                }
                BigDecimal bigDecimal = new BigDecimal(myCartAdapter.getData().get(position).getGoodsListEntity().getSell_price());
                BigDecimal bigDecimal1 = new BigDecimal(myCartAdapter.getData().get(position).getGoodsListEntity().getNiu_score());
                BigDecimal bigDecima2 = new BigDecimal(String.valueOf(goodsNumber));
                BigDecimal bigDecima21 = new BigDecimal("2");
                Log.d("打印", "onSuccess: " + myCartAdapter.getData().get(position).getGoodsListEntity().getIs_service());
                if (!TextUtils.isEmpty(myCartAdapter.getData().get(position).getGoodsListEntity().getIs_service())) {
                    if (Integer.parseInt(myCartAdapter.getData().get(position).getGoodsListEntity().getIs_service()) == 0) {
                        myCartAdapter.getData().get(position).getGoodsListEntity().setSum(bigDecimal.multiply(bigDecima2).toString());
                        myCartAdapter.getData().get(position).getGoodsListEntity().setCount_score(bigDecimal1.multiply(bigDecima2).toString());
                    } else if (Integer.parseInt(myCartAdapter.getData().get(position).getGoodsListEntity().getIs_service()) == 1) {
                        myCartAdapter.getData().get(position).getGoodsListEntity().setSum(bigDecimal.multiply(bigDecima2).multiply(bigDecima21).toString());
                        myCartAdapter.getData().get(position).getGoodsListEntity().setCount_score(bigDecimal1.multiply(bigDecima2).multiply(bigDecima21).toString());
                    }
                } else {
                    myCartAdapter.getData().get(position).getGoodsListEntity().setSum(bigDecimal.multiply(bigDecima2).multiply(bigDecima21).toString());
                    myCartAdapter.getData().get(position).getGoodsListEntity().setCount_score(bigDecimal1.multiply(bigDecima2).multiply(bigDecima21).toString());
                }
                myCartAdapter.notifyDataSetChanged();
                sumMoney();
            }
        });
    }

    /**
     * 计算价格和是否全选(需要整体循环计算的都在这里加)
     */
    private void sumMoney() {
        double moneyRmb = 0;
        double moneyNjf = 0;
        int select = 0;
        for (int a = 0; a < myCartAdapter.getData().size(); a++) {
            if (myCartAdapter.getData().get(a).isSelect()) {
                BigDecimal bigDecimal = new BigDecimal(myCartAdapter.getData().get(a).getGoodsListEntity().getSell_price());
                BigDecimal bigDecimal1 = new BigDecimal(myCartAdapter.getData().get(a).getGoodsListEntity().getNiu_score());
                BigDecimal bigDecima2 = new BigDecimal(myCartAdapter.getData().get(a).getGoodsListEntity().getCount());
                BigDecimal bigDecima21 = new BigDecimal("2");
                if (!TextUtils.isEmpty(myCartAdapter.getData().get(a).getGoodsListEntity().getIs_service())) {
                    if (!TextUtils.isEmpty(myCartAdapter.getData().get(a).getGoodsListEntity().getPayment_options())) {
                        if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getPayment_options()) == 0) {
                            BigDecimal b = new BigDecimal(String.valueOf(moneyRmb));
                            if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getIs_service()) == 0) {
                                moneyRmb = bigDecimal.multiply(bigDecima2).add(b).doubleValue();
                            } else if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getIs_service()) == 1) {
                                moneyRmb = bigDecimal.multiply(bigDecima2).multiply(bigDecima21).add(b).doubleValue();
                            }
                        } else if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getPayment_options()) == 1) {
                            BigDecimal c = new BigDecimal(String.valueOf(moneyNjf));
                            if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getIs_service()) == 0) {
                                moneyNjf = bigDecimal1.multiply(bigDecima2).add(c).doubleValue();
                            } else if (Integer.parseInt(myCartAdapter.getData().get(a).getGoodsListEntity().getIs_service()) == 1) {
                                moneyNjf = bigDecimal1.multiply(bigDecima2).multiply(bigDecima21).add(c).doubleValue();
                            }
                        }
                    }

                }
                select++;
            }
        }
        if (select == 0) {
            cartImgAll.setImageResource(R.drawable.icon_unselected_1_2_0);
            isSelelctAll = false;
        } else if (select < myCartAdapter.getData().size()) {
            cartImgAll.setImageResource(R.drawable.icon_unselected_1_2_0);
            isSelelctAll = false;
        } else {
            cartImgAll.setImageResource(R.drawable.icon_selected_1_2_0);
            isSelelctAll = true;
        }
        if (moneyRmb > 0 && moneyNjf > 0) {
            cartFootCl2.setVisibility(View.VISIBLE);
            cartFootTxt2.setVisibility(View.VISIBLE);
            cartFootTxt3.setVisibility(View.VISIBLE);
        } else if (moneyRmb > 0) {
            cartFootCl2.setVisibility(View.VISIBLE);
            cartFootTxt2.setVisibility(View.GONE);
            cartFootTxt3.setVisibility(View.GONE);
        } else if (moneyNjf > 0) {
            cartFootCl2.setVisibility(View.GONE);
            cartFootTxt2.setVisibility(View.GONE);
            cartFootTxt3.setVisibility(View.VISIBLE);
        } else {
            cartFootCl2.setVisibility(View.GONE);
            cartFootTxt2.setVisibility(View.GONE);
            cartFootTxt3.setVisibility(View.GONE);
        }
        cartFootCl2.setText(String.valueOf(moneyRmb));
        cartFootTxt3.setText(String.valueOf(moneyNjf));
    }

    private List<CartBaseEntity> getSubmitData() {
        entitySubmitList = new ArrayList<>();
        for (int a = 0; a < entityList.size(); a++) {
            if (entityList.get(a).isSelect()) {
                entitySubmitList.add(entityList.get(a));
            }
        }
        return entitySubmitList;
    }

    @Override
    public void updateCart() {
        getCart(true);
    }
}
